﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Aierp.Utility;
using System.Collections.Concurrent;
using Aierp.Repository.Implements;
using Aierp.Utility.Core;
using Aierp.SystemEntities.System;
using Aierp.SystemRepository.Models;
using Microsoft.Extensions.Caching.Memory;

namespace Aierp.Controllers
{
    [Route("api/[controller]")]
    public class NavigationController : ControllerBase
    {
        NavigationRepository Repository { get; set; }
        SysVisitor SysVisitor { get; set; }
        private readonly IMemoryCache _cache;
        public NavigationController(NavigationRepository navigation, SysVisitor sysVisitor, IMemoryCache memoryCache)
        {
            Repository = navigation;
            SysVisitor = sysVisitor;
            _cache = memoryCache;
        }

        /// <summary>
        /// 获取一级导航列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetList")]
        public async Task GetList()
        {
            await GetNavigation("0"); ;
        }

        /// <summary>
        /// 获取二级导航列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetSubList/{id}")]
        public async Task GetSubList(string id)
        {
            //return GetNavigation(id);
            await GetNavigation(id); ;
        }

        private async Task GetNavigation(string parentId)
        {
            var pageParam = this.GetPageParam();
            var ret = Repository.GetList(pageParam.Limit, pageParam.Offset, parentId, pageParam.Order);
            await this.WriteAsync(ret); 
        }

        /// <summary>
        /// 获取单个
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET api/values/5
        [HttpGet("{id}")]
        public async Task Get(int id)
        {
            var model = Repository.FindById(id);
            //return JSONhelper.ToJson(model);

            if (model == null)
            {
                await WriteFailJson();
                return;
            }
            await WriteResultJson(model);
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task GetAll()
        {
            var list = Repository.FindAll();
            //return JSONhelper.ToJson(list);
            await WriteResultJson(list);
        }

        [HttpGet("GetTree")]
        public async Task GetTree()
        {
            var list = Repository.FindAll();
            var nav = GetChildMenu(list, 0);
            //return JSONhelper.ToJson(nav);
            await WriteResultJson(nav);
        }

        /// <summary>
        /// 获取树形菜单
        /// </summary>
        /// <param name="list"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private static IList<NavTreeModel> GetChildMenu(IList<Sys_Navigations> list, int id)
        {
            IList<NavTreeModel> entitys = new List<NavTreeModel>();
            foreach (var item in list.Where(it => it.ParentID == id))
            {
                var entity = new NavTreeModel();
                entity.KeyId = item.KeyId;
                entity.Sortnum = item.Sortnum;
                entity.NavTitle = item.NavTitle;
                entity.NavTag = item.NavTag;

                entity.Linkurl = item.Linkurl;
                entity.IsVisible = item.IsVisible;
                entity.iconCls = item.iconCls;
                entity.ParentID = item.ParentID;

                entity.id = entity.KeyId;
                entity.text = entity.NavTitle;

                entity.nodes = GetChildMenu(list, item.KeyId);
                entitys.Add(entity);
            }
            entitys = entitys.OrderByDescending(c => c.KeyId).ToList();
            return entitys;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        // POST api/values
        [HttpPost]
        public async Task Post(string value)
        {
            //检查用户是否有权限操作
            if(!await CheckUser(SysVisitor)) return;

            ////获取用户对象
            var model = GetModel<Sys_Navigations>();

            if (model.NavTitle.IsEmpty() || model.Linkurl.IsEmpty())
            {
                await this.WriteSpecReasonJson("保存失败，错误信息如下：必填写表单不能为空！");
                return;
            }

            var result = Repository.Add(model);

            if (result > 0) await this.WriteSucessJson();

            if (result == -2) await this.WriteSpecReasonJson("菜单已存在，请更换菜单名称！");
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <returns></returns>
        [HttpPost("Update")]
        public async Task Update()
        {
            //检查用户是否有权限操作
            if (!await CheckUser(SysVisitor)) return;

            //获取用户对象
            var model = GetModel<Sys_Navigations>();

            if (model.NavTitle.IsEmpty() || model.Linkurl.IsEmpty())
            {
                await this.WriteSpecReasonJson("保存失败，错误信息如下：必填写表单不能为空！");
                return;
            }
            var result = Repository.Update(model);
            if (result > 0)
            {
                await this.WriteSucessJson();
                return;
            }
            switch (result)
            {
                case -2:
                    await this.WriteSpecReasonJson("保存失败，错误信息如下：菜单名称已存在，请更换菜单名称！");
                    return;
                case -9:
                    await this.WriteSpecReasonJson("保存失败，错误信息如下：菜单不存在！");
                    return;
            }
            await WriteFailJson();
        }

        /// <summary>
        /// 停用
        /// </summary>
        /// <param name="id"></param>
        // DELETE api/values/5
        [HttpDelete("{id}")]
        public async Task Delete(int id)
        {
            //检查用户是否有权限操作
             if (!await CheckUser(SysVisitor)) return;;

            if (id == 0)
            {
                await this.WriteSpecReasonJson("系统中没有这个菜单！");
                return;
            }

            var result = Repository.Remove(id);

            if (result > 0)
            {
                await this.WriteSucessJson();
                return;
            }

            switch (result)
            {
                case -2:
                    await this.WriteSpecReasonJson("系统中找不到这个菜单！");
                    return;
                case -8:
                    await this.WriteSpecReasonJson("该菜单已经被用户使用，不能删除！");
                    return;
                case -9:
                    await this.WriteSpecReasonJson("菜单不能删除！");
                    break;
            }
        }

        /// <summary>
        /// 获取主页面框架左侧菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetClientsDataJson")]
        public ConcurrentDictionary<string,string> GetClientsDataJson()
        {
            var currentUser = SysVisitor.CurrentUser;
            return Repository.GetClientsDataJson(0, currentUser);
        }

        /// <summary>
        /// 更新版本
        /// </summary>
        /// <returns></returns>
        [HttpGet("UpdateVersion")]
        public async Task UpdateVersion()
        {
            //检查用户是否有权限操作
            if (!await CheckUser(SysVisitor)) return;
            
            var result = Repository.UpdateVersion();
            //查询数据库获取最新的版本号
            var htmlVersion = Repository.FindHtmlVersion();
            //将最新的版本号写入缓存
            if (htmlVersion > 0)
            {
                _cache.Set("HtmlVersion", htmlVersion, TimeSpan.FromDays(15));
            }

            if (result > 0)
            {
                await this.WriteSucessJson();
                return;
            }
            await WriteFailJson();
        }

    }

}
